package com.pan.download5.driver;

import com.pan.crawler.Page;
import com.pan.download5.config.TaskHandleConfig;
import com.pan.download5.ctrl.ChapterSyncWriter;
import com.pan.download5.ctrl.TaskSyncPublish;
import com.pan.entity.Chapter;

import java.util.concurrent.CountDownLatch;

/**
 *
 * 这个类已经被我废弃了，请用 TaskHandleImpl2
 * 废弃原因，
 * 部分原因 可以参考com.pan.download5.ctrl.ChapterSyncWriterImpl
 *
 * 即章节任务处理应该包含标题清洗写入内容的拼接等，
 * 而且另外一个问题，这里的Page是作为一个实例在构造函数中注入为成员变量的，
 * 但是Page的创建是一个比费时的行为应该放入多线程中去实现
 *
 *
 *
 * 多线程里的线程逻辑
 * 对章节任务进行处理，直到没有任务
 */
public class TaskHandleImpl implements TaskHandle, TaskHandleConfig {

    private Page page;
    private TaskSyncPublish taskPublish;
    private ChapterSyncWriter chapterSyncWriter;
    private CountDownLatch countDownLatch;

    public TaskHandleImpl(Page page, TaskSyncPublish taskPublish,
                          ChapterSyncWriter chapterSyncWriter, CountDownLatch countDownLatch) {
        this.page = page;
        this.taskPublish = taskPublish;
        this.chapterSyncWriter = chapterSyncWriter;
        this.countDownLatch = countDownLatch;
    }

    private final int errorCount = this.getErrorCount();
    private final int errorWait = this.getErrorWait();//Unit: Milli Seconds

    @Override
    public void run() {
        while (true) {
            Chapter task = taskPublish.publish();
            if (task == null){
                try {Thread.sleep(errorWait);} catch (InterruptedException e) {
                    throw new RuntimeException(e);}
                task = taskPublish.publish();
                if (task == null) break;
            }
            int id = task.getId();
            String title = task.getTitle();
            String content = "";
            for (int i = 0; i < errorCount; i++) {
                try {
                    content  = page.get(task);
                    break;
                }catch (Exception e){
                    String errorMessage = i+" id: " + id + " title: " + title + "  爬取失败";
                    System.out.println(errorMessage);
                    System.out.println(e);
                    if (i == errorCount-1) {content = errorMessage; break;}
                }
                try {Thread.sleep(errorWait);}
                catch (InterruptedException e) {throw new RuntimeException(e);}
            }
            chapterSyncWriter.writeChapter(id,title,content);
            System.out.println("爬取章节完成：" + title);
        }
        page.close();
        countDownLatch.countDown();
    }
}
